package imgshare.common.listener;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import imgshare.common.event.FollowCreatedEvent;
import imgshare.common.sse.SseEmitters;
import imgshare.model.Notification;
import imgshare.model.User;
import imgshare.service.NotificationService;
import imgshare.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Component
public class FollowCreatedListener {

    @Autowired
    SseEmitters sseEmitters;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private UserService userService;

    private static final Log log = LogFactory.get();

    @Async
    @EventListener(FollowCreatedEvent.class)
    public void handleFollowCreated(FollowCreatedEvent event) {

        log.info("监听到新的FollowCreatedEvent,SubjectId:{};ObjectId:{}",event.getSubjectId(),event.getObjectId());

        Notification notification = new Notification();
        notification.setType("new_follower");
        notification.setContent("有用户关注了你");
        notification.setRelatedUserId(event.getSubjectId());
        notification.setReceiverId(event.getObjectId());
        notification.setCreatedTime(LocalDateTime.now());
        notificationService.create(notification);

        sseEmitters.sendMessage(event.getObjectId(),notification);
    }
}
